import { BaseEditor } from './BaseEditor'
import { CellValue } from '../types'

export class SelectEditor extends BaseEditor {
  protected select: HTMLSelectElement | null = null
  
  protected createElement(value: CellValue): HTMLElement {
    const editOptions = this.getEditOptions()
    
    // 创建下拉框
    this.select = document.createElement('select')
    
    // 设置属性
    if (editOptions.required) {
      this.select.required = true
    }
    
    if (editOptions.readonly) {
      this.select.disabled = true
    }
    
    // 添加选项
    const options = editOptions.options || (Array.isArray(this.column.editOptions) ? this.column.editOptions : [])
    
    // 添加空选项
    if (!editOptions.required) {
      const emptyOption = document.createElement('option')
      emptyOption.value = ''
      emptyOption.textContent = editOptions.placeholder || '请选择...'
      this.select.appendChild(emptyOption)
    }
    
    // 添加其他选项
    options.forEach((opt: any) => {
      const option = document.createElement('option')
      option.value = String(opt.value)
      option.textContent = opt.label
      if (opt.disabled) {
        option.disabled = true
      }
      if (this.select) {
        this.select.appendChild(option)
      }
    })
    
    // 设置初始值
    this.setValue(value)
    
    return this.select
  }
  
  getValue(): CellValue {
    if (!this.select) return null
    const value = this.select.value
    if (!value) return null
    
    // 尝试转换类型
    const options = this.getEditOptions().options || (Array.isArray(this.column.editOptions) ? this.column.editOptions : [])
    const selectedOption = options.find((opt: any) => String(opt.value) === value)
    
    return selectedOption ? selectedOption.value : value
  }
  
  setValue(value: CellValue): void {
    if (!this.select) return
    this.select.value = value != null ? String(value) : ''
  }
  
  protected applyCustomStyles(): void {
    if (!this.select) return
    
    // 下拉框的特殊样式
    this.select.style.cursor = 'pointer'
    this.select.style.paddingRight = '24px' // 留出下拉箭头的空间
  }
} 